uniform sampler2D suggestiveContours, depthTexture;
uniform vec2 screenSize;
uniform float threshold;
uniform vec4 color;

 
#define s2(a, b)		temp = a; a = min(a, b); b = max(temp, b);
#define mn3(a, b, c) 		s2(a, b); s2(a, c);
#define mx3(a, b, c)		s2(b, c); s2(a, c);

#define mnmx3(a, b, c)		mx3(a, b, c); s2(a, b);                                   // 3 exchanges
#define mnmx4(a, b, c, d)	s2(a, b); s2(c, d); s2(a, c); s2(b, d);                   // 4 exchanges
#define mnmx5(a, b, c, d, e)	s2(a, b); s2(c, d); mn3(a, c, e); mx3(b, d, e);           // 6 exchanges
#define mnmx6(a, b, c, d, e, f) s2(a, d); s2(b, e); s2(c, f); mn3(a, b, c); mx3(d, e, f); // 7 exchanges


          
void main(void) { 

  float depth;
  float temp, pixel;
  float minDepth= 1.0;
  float centerDepth= texture2D(depthTexture, gl_FragCoord.xy/screenSize).x;


  float pixels[9];
  int i;
  
  vec2 offsets[9];
  
  offsets[0]=   vec2(-1.0, -1.0);
  offsets[1]=   vec2(-1.0,  0.0);
  offsets[2]=   vec2(-1.0,  1.0);
  offsets[3]=   vec2( 0.0, -1.0);
  offsets[4]=   vec2( 0.0,  0.0);	
  offsets[5]=   vec2( 0.0,  1.0);
  offsets[6]=   vec2( 1.0, -1.0);
  offsets[7]=   vec2( 1.0,  0.0);
  offsets[8]=   vec2( 1.0,  1.0);	
  

  vec2 offset;

  // find minimum and maximum
  for(i=0; i<9; i++){
    pixels[i]= texture2D(suggestiveContours, (gl_FragCoord.xy+offsets[i])/screenSize).r;
    if(centerDepth==1.0){
      depth= texture2D(depthTexture, (gl_FragCoord.xy+offsets[i])/screenSize).x;
      if(depth<minDepth) minDepth= depth;
    }	
  }  
  
  // Starting with a subset of size 6, remove the min and max each time
  mnmx6(pixels[0], pixels[1], pixels[2], pixels[3], pixels[4], pixels[5]);
  mnmx5(pixels[1], pixels[2], pixels[3], pixels[4], pixels[6]);
  mnmx4(pixels[2], pixels[3], pixels[4], pixels[7]);
  mnmx3(pixels[3], pixels[4], pixels[8]);

  if(pixels[4]!=0.0){
    gl_FragColor= vec4(color.rgb, pixels[4]);
    if(centerDepth==1.0) gl_FragDepth= minDepth;
    else gl_FragDepth= gl_FragCoord.z;	
  }  
  else discard;

  //gl_FragColor= texture2D(suggestiveContours, (gl_FragCoord.xy)/screenSize);
}
